import React, { useState, useEffect, useRef } from "react";
import { Space, Tooltip, Button as AButton } from "antd";
import Icon from "@ant-design/icons";
import UploadModal from "../UploadModal/index";
import UploadPreviewModal from "../UploadPreviewModal/index";
import { useTranslation } from "react-i18next";
import { omit } from "lodash-es";
import { isArray } from "@/utils/is";

interface BasicUploadProps {
	value: string[];
	onChange?: (value: string[]) => void;
	onDelete?: (record: Record<string, any>) => void;
	onPreviewDelete?: (url: string) => void;
	emptyHidePreview?: boolean;
	showPreviewNumber?: boolean;
}

const BasicUpload: React.FC<BasicUploadProps> = ({
	value,
	onChange,
	onDelete,
	onPreviewDelete,
	emptyHidePreview = false,
	showPreviewNumber = false
}) => {
	const [fileList, setFileList] = useState<string[]>([]);
	const attrsRef = useRef<any>({});
	const { t } = useTranslation();

	useEffect(() => {
		setFileList(isArray(value) ? value : []);
	}, [value]);

	const bindValue = omit({ ...attrsRef.current }, "onChange");

	const handleUploadOpen = () => {
		// Open upload modal logic here
	};

	const handlePreviewOpen = () => {
		// Open preview modal logic here
	};

	const handleChange = (urls: string[]) => {
		setFileList([...fileList, ...(urls || [])]);
		onChange?.([...fileList, ...(urls || [])]);
	};

	const handlePreviewChange = (urls: string[]) => {
		setFileList(urls || []);
		onChange?.(urls || []);
	};

	const handleDelete = (record: Record<string, any>) => {
		onDelete?.(record);
	};

	const handlePreviewDelete = (url: string) => {
		onPreviewDelete?.(url);
	};

	return (
		<div>
			<Space>
				<AButton type="primary" onClick={handleUploadOpen}>
					<Icon component={() => <span className="carbon-cloud-upload" />} />
					{t("component.upload.upload")}
				</AButton>
				{(!emptyHidePreview || fileList.length > 0) && (
					<Tooltip placement="bottom" title={`${t("component.upload.uploaded")}${fileList.length ? ` ${fileList.length}` : ""}`}>
						<AButton onClick={handlePreviewOpen}>
							<Icon component={() => <span className="bi-eye" />} />
							{showPreviewNumber && fileList.length && ` ${fileList.length}`}
						</AButton>
					</Tooltip>
				)}
			</Space>
			<UploadModal {...bindValue} previewFileList={fileList} onChange={handleChange} onDelete={handleDelete} />
			<UploadPreviewModal value={fileList} onChange={handlePreviewChange} onDelete={handlePreviewDelete} />
		</div>
	);
};

export default BasicUpload;
